package com.liangtian.mdm.dm.config.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.constant.TableConst;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.dm.common.util.RequestUtils;
import com.liangtian.mdm.dm.config.model.AttrConfig;
import com.liangtian.mdm.dm.config.service.AttrConfigService;
import com.liangtian.mdm.dm.model.model.Model;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/config")
public class AttrConfigController {

    @Autowired
    private AttrConfigService attrConfigService;

    //当前用户
    ////@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;


    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/queryAttributesList", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject queryAttributes(HttpServletRequest request) {
        Map paramMap = RequestUtils.paramToMap(request);
        PageInfo pageInfo = attrConfigService.queryAttributesList(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/updateAttrConfig", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public JSONObject updateAttrConfig(HttpServletRequest request, AttrConfig attrConfig) {
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        JSONObject jsonObject = new JSONObject();
        try {
            attrConfigService.updateAttrConfig(attrConfig);
            rMsg.setRspCode(0);
        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/queryAttrConfig", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String queryAttrConfig(HttpServletRequest request) {
        String rs = "";
        try {
            String modelId = request.getParameter("model_id");
            String attrId = request.getParameter("attr_id");
            AttrConfig attr = attrConfigService.queryAttrConfig(modelId, attrId);
            rs = JSON.toJSONString(attr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }

    @ResponseBody
    @RequestMapping(value = "/queryAllModelTables", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String queryAllModelTables(HttpServletRequest request) {
        String rst = null;
        try {
            String classType = request.getParameter("classType");
            String model_id = request.getParameter("modelId");
            List<Model> models = attrConfigService.queryAllModelTables(classType, model_id);
            rst = JSON.toJSONString(models);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }

    @ResponseBody
    @RequestMapping(value = "/queryAttributesListIsParent", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String queryAttributesListIsParent(HttpServletRequest request) {
        String rst = null;
        try {
            String modelId = request.getParameter("modelId");
            String isP = request.getParameter("isP");
            Map<String, String> map = new HashMap<>();
            map.put("modelId", modelId);
            map.put("isP", isP);
            List<AttrConfig> configs = attrConfigService.queryAttributesListIsParent(map);
            rst = JSON.toJSONString(configs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }

    @ResponseBody
    @RequestMapping(value = "/queryTableColumns", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String queryTableColumns(HttpServletRequest request) {
        String rst = null;
        try {
            String modelId = request.getParameter("modelId");
            String attrShowColumns = request.getParameter("attrShowColumns");
            List<AttrConfig> configs = new ArrayList<AttrConfig>();
            List<AttrConfig> attributes = attrConfigService.queryModelTable4Column(modelId);

            if (attrShowColumns != null) {
                String[] showColumn = attrShowColumns.split(",");
                for (int i = 0; i < showColumn.length; i++) {
                    String column = showColumn[i];
                    for (int j = 0; j < attributes.size(); j++) {
                        AttrConfig attrConfigShow = attributes.get(j);
                        String attrColumn = attrConfigShow.getAttrColumn();
                        if (attrColumn.equals(column)) {
                            configs.add(attrConfigShow);
                        }
                    }
                }
                rst = JSON.toJSONString(configs);
            } else {
                rst = JSON.toJSONString(attributes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }

    /**
     * <p>TODO 新增一个方法，判断，如果选的数据模型是父子树，那么，给一个树来源的选项</p>
     * <p>@param request
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年6月16日下午3:06:35
     */
    @ResponseBody
    @RequestMapping(value = "/getTabViewColum", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String getTabViewColum(HttpServletRequest request) {
        String rst = null;
        try {
            String modelId = request.getParameter("modelId");
            String type = request.getParameter("type");
            List<AttrConfig> configs = new ArrayList<AttrConfig>();
            List<AttrConfig> attributes = attrConfigService.queryModelTable4Column(modelId);

            if (type.equals("tree")) {
                for (int j = 0; j < attributes.size(); j++) {
                    AttrConfig attrConfig = attributes.get(j);
                    //String attrColumn = attrConfig.getAttrColumn();
                    int isParant = attrConfig.getIsParentType();
                    if (isParant == 1) {//如果是父子级关系
                        configs.add(attrConfig);
                    }
                }
                rst = JSON.toJSONString(configs);
            }
//			  else if(type.equals("pop")){
//				  rst = JSON.toJSONString(attributes);
//			}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }


    @ResponseBody
    @RequestMapping(value = "/queryCascadeAttr", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String queryCascadeAttr(HttpServletRequest request) {
        String rst = null;
        try {
            List<AttrConfig> cascadeAttrList = attrConfigService.queryCascadeAttr(request.getParameter("modelId"));
            rst = JSON.toJSONString(cascadeAttrList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }

    @ResponseBody
    @RequestMapping(value = "/querySelectedAttr", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String querySelectedAttr(HttpServletRequest request, AttrConfig attrConfig) {
        String column = attrConfig.getDataSourceColumn();
        String table = attrConfig.getDataSourceTable();
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ID, ").append(column.replace(",", "||'_'||"))
                .append(" NAME FROM ").append(TableConst.TABLEPREFIX).append(table)
                .append(" WHERE STATE=4 AND STATUS=0 ");
        String rst = null;
        try {
            List<Map> rest = attrConfigService.querySelectedAttr(sql.toString());
            rst = JSON.toJSONString(rest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }

    @ResponseBody
    @RequestMapping(value = "/queryAttr", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String queryAttr(HttpServletRequest request) {
        String rst = null;
        try {
            List<AttrConfig> attrBc = new ArrayList<AttrConfig>();
            //List<AttrConfig> attrLst = new ArrayList<AttrConfig>();
            //在这里加个筛选条件
            String modelId = request.getParameter("modelId");
            String BC = request.getParameter("BC");
            List<AttrConfig> attrs = attrConfigService.queryAttr(modelId);
            if (BC != null) {
                for (int i = 0; i < attrs.size(); i++) {
                    String type = attrs.get(i).getDataType();
                    if (type != null && (type.equals("BLOB") || type.equals("CLOB"))) {
                        continue;
                    } else {
                        attrBc.add(attrs.get(i));
                    }
                }
                rst = JSON.toJSONString(attrBc);

            } else {
//				for (int i = 0; i < attrs.size(); i++) {
//					int isNul = attrs.get(i).getIsNull();
//					if(isNul == 1){
//						attrLst.add(attrs.get(i));
//					}
//				}
                rst = JSON.toJSONString(attrs);
            }
        } catch (Exception e) {
        }
        return rst;
    }

    @ResponseBody
    @RequestMapping(value = "/queryModelType", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String queryModelType(HttpServletRequest request) {
        String rst = null;
        try {
            Model model = attrConfigService.queryModelType(request.getParameter("modelId"));
            // 数据类型【0-列表、1-父子树、2-分类树】
            rst = model.getClassType();
        } catch (Exception e) {
        }
        return rst;
    }

    /*
     * 初始化模型含义码的值
     * */
    @ResponseBody
    @RequestMapping(value = "/initHyCodeValues", method = RequestMethod.POST)
    public String initHyCodeValues(HttpServletRequest request) {
        String rst = null;
        try {
            Map<String, Object> param = RequestUtils.paramToMap(request);
            List<AttrConfig> acLst = attrConfigService.initHyCodeValues(param);
            rst = JSON.toJSONString(acLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }

    /*
     * 初始化模型枚举类型含义码的编码值
     * */
    @RequestMapping(value = "/initSelectCodeValues", method = RequestMethod.POST)
    @ResponseBody
    public String initSelectCodeValues(HttpServletRequest request) {
        String rst = null;
        try {
            Map<String, Object> param = RequestUtils.paramToMap(request);
            List<AttrConfig> ac = attrConfigService.initHyCodeValues(param);
            String dataSourceTable = ac.get(0).getDataSourceTable();
            Map<String, Object> cond = new HashMap<>();
            cond.put("hyDataSourceTable", dataSourceTable);
            List<AttrConfig> acLst = attrConfigService.initHyCodeValues(cond);
            rst = JSON.toJSONString(acLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }

    @RequestMapping(value = "/queryModelCodeAttrs", method = RequestMethod.POST)
    @ResponseBody
    public String queryModelCodeAttrs(HttpServletRequest request) {
        String rst = null;
        try {
            Map<String, Object> param = RequestUtils.paramToMap(request);
            param.put("moduleType", "4");
            //获取session中用户
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
            param.put("userId", String.valueOf(user.getUserId()));
            List<AttrConfig> ac = attrConfigService.queryCodeAttrs(param);
            rst = JSON.toJSONString(ac);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }

    //校验用户输入的表名是否正确
    @ResponseBody
    @RequestMapping(value = "/checkTabNoNameValide", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public JSONObject checkTabNoNameValide(HttpServletRequest request) {
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        JSONObject jsonObject = new JSONObject();
        try {
            String tableName = request.getParameter("tabName");
            boolean flag = attrConfigService.checkTabNoNameValide(tableName);
            if (flag) {
                rMsg.setRspCode(0);
                rMsg.setRspMsg("success");
            } else {
                rMsg.setRspCode(-1);
                rMsg.setRspMsg("false");
            }
        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
            rMsg.setRspMsg("false");
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    /**
     * <p>TODO 用户输入表名成功的话，动态的加载该表名下面的属性列的集合</p>
     * <p>@param request
     * <p>@return </p>
     *
     * @author : xiaoliu
     * @date :2017年8月1日下午4:25:55
     */
    @ResponseBody
    @RequestMapping(value = "/queryTabNoNameColumns", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public String queryTabNoNameColumns(HttpServletRequest request) {
        String rst = null;
        try {
            String tableName = request.getParameter("tableName");
            List<AttrConfig> acList = attrConfigService.queryTabNoNameColumns(tableName);

            rst = JSON.toJSONString(acList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rst;
    }

}
